package com.buka.order.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.buka.cart.fegin.CartFegin;
import com.buka.order.config.RabbitMqConfig;
import com.buka.order.mapper.OrderMapper;
import com.buka.order.service.OrderService;
import com.buka.order.service.TaskService;
import com.buka.pojo.Order;
import com.buka.pojo.Task;
import com.buka.server.feign.ProductDetailsFeign;
import com.buka.server.pojo.ProductDetails;
import com.buka.utils.TokenDecode;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartFegin cartFeign;
    @Autowired
    private ProductDetailsFeign productDetailsFeign;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TokenDecode tokenDecode;
    @Autowired
    private TaskService taskService;
//    @Override
//    public void add(Order order) {
//        order.setId(IdWorker.getId());
//        orderMapper.insertSelective(order);
//        //购物车？
//        cartFeign.Delete(order.getProductId().toString());
//        //库存
//        productDetailsFeign.reducedInventory(order.getProductId(),order.getNum());
//
//    }



    @Override
    public void delete(Long id) {
        Order order = new Order();
        order.setId(id);
        order.setIsDelete(1);
        this.update(order);
    }

    @Override
    public void update(Order order) {
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public List<Order> findAll() {
        Example example = new Example(Order.class);
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete", 0);
        List<Order> orders = orderMapper.selectByExample(example);
        return orders;
    }

    @Override
    public void add(Order order) {
        //1生成订单
        order.setBuyerName(tokenDecode.getUserInfo().get("user_name"));
        order.setId(IdWorker.getId());
        orderMapper.insertSelective(order);
        //向任务表中添加数据
        //------------------------
        Task taskGoods = new Task();
        taskGoods.setMqRoutingkey(RabbitMqConfig.GOODS_QUEUE);
        taskGoods.setRequestBody(JSON.toJSONString(order));
        taskGoods.setCreateTime(new Date());
        taskGoods.setTaskType("1");
        taskService.add(taskGoods);
        //发送任务到mq
        rabbitTemplate.convertAndSend("", RabbitMqConfig.GOODS_QUEUE,taskGoods);
           
    }

    @Override
    public Page<Order> findAllPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return (Page<Order>) this.findAll();
    }

    @Override
    public Order findById(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        return order;
    }

    @Override
    public List<Order> findList(Map<String, Object> map) {
        Example example = new Example(Order.class);
        //根据下单时间倒序查询
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        //查询未删除的
        criteria.andEqualTo("isDelete", 0);
        Set<String> strings = map.keySet();

        for (String string : strings) {
            //如果有值，则查询
            if (StringUtils.isNotEmpty(map.get(string).toString())) {
                if (string.equals("buyerName") || string.equals("id")) {
                    //如果是买家名称或者订单id，模糊查询
                    criteria.andLike(string, "%" + map.get(string).toString() + "%");
                } else if (string.equals("startEnd")) {
                    //如果是起止时间，则查询下单时间在这个时间范围内的
                    String[] startEnd = map.get(string).toString().split(",");
                    if (startEnd.length == 2) {
                        criteria.andBetween("createTime", startEnd[0], startEnd[1]);
                    }
                } else {
                    //如果是其他字段，则查询
                    criteria.andEqualTo(string, map.get(string));
                }
            }
        }
        List<Order> orders = orderMapper.selectByExample(example);

        return orders;
    }

    @Override
    public Page<Order> findListPage(Map<String, Object> map, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return (Page<Order>) this.findList(map);
    }

    @Override
    @Transactional
    public void buyMore(List<Order> orders) {
        for (Order order : orders) {
            add(order);
        }
    }
}